﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using CommonTools;
using WeifenLuo.WinFormsUI.Docking;
using shop.Model;
using shop.Bll;
using System.Drawing.Printing;
using shop.Logi;
using shop.Bll.cost;
using shop.cost;
using shop.daifa;
using shop.Bll.BasicInfo;
using shop.job;
using CommonTools.Controls;

namespace shop
{
    public partial class MenuForm : DockContent
    {

        #region 构造函数

        public MenuForm()
        {
            InitializeComponent();

            //
            this.Lab_user.Text = shop.Bll.UserBll.CurrentUser?.Name;
            this.toolStrip_ver.Text = "版本: "+myApp.MyVersion ;

            //检查权限
            RightHelper.CheckRight(this);


            #region 自定义控件

            //隐藏tabControl的标签 
            this.MenuTab.ItemSize = new Size(0, 1);
            this.MenuTab.Appearance = TabAppearance.FlatButtons;
            foreach (TabPage page in this.MenuTab.TabPages)
            {
                page.Text = "";
            }
            #endregion

            #region 切换用户

            shop.Bll.UserBll.UserChanged += UserBll_UserChanged;

            #endregion

        }

        #endregion


        #region 切换用户, 权限, 语言

        private void btn_changeUser_Click(object sender, EventArgs e)
        {
            Account act = new Account(myApp.Owner);
            act.ShowDialog();
        }

        private void btn_permission_Click(object sender, EventArgs e)
        {
            myApp.MainDock.AddForm2Layer<RightManagerForm>();
        }


        /// <summary> 切换用户 </summary>
        private void UserBll_UserChanged()
        {
            this.Lab_user.Text = shop.Bll.UserBll.CurrentUser.Name;
            //检查权限
            this.DoInvoke(() =>
            RightHelper.CheckRight(this)
            );
        }

        /// <summary> 更改语言事件 </summary>
        private void LanguageHelper_OnChangeLanguaged(CultureInfo info)
        {
            //shop.Model.LanguageSet.SetLanguage(this);

            //this.StatusLabel_Lang.Text = info.NativeName;

            //// 版本号
            //this.toolStrip_ver.Text = string.Format(CN.text_version, Program.MyVersion);

            //if (Program.Owner != null)
            //{
            //    this.label_title.Text = Program.Owner.Title;  //标题
            //    this.Text = Program.Owner.Title;
            //}

            //this.TabText = CN.text_HomePage;   // "主页";

            //this.toolTip1.SetToolTip(this.btn_changeUser, CN.tip_changeUser);
            //this.toolTip1.SetToolTip(this.btn_permission, CN.tip_Right);

            ////左侧导航栏
            //foreach (GtOutlookBarButton button in this.outlookBar.Buttons)
            //{
            //    string s = CN.ResourceManager.GetString(button.Name);
            //    if (string.IsNullOrEmpty(s) == false)
            //        button.Text = s;
            //}


        }


        /// <summary> 更改语言后事件 </summary>
        private void LanguageHelper_AfterChangeLanguaged()
        {
            //右侧报表 
            //MenuTab_Selected(this.MenuTab, new TabControlEventArgs(this.MenuTab.SelectedTab, this.MenuTab.SelectedIndex, TabControlAction.Selected));
        }



        #endregion
        

        #region 最近的文件

        /// <summary>
        /// 最近的文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tool_files_ButtonClick(object sender, EventArgs e)
        {
            ToolStripMenuItem fileMenu;
            if (this.StatusLabel_files.DropDownItems.Count == 0)
            {
                for (int i = 0; i < 50; i++)
                {
                    fileMenu = new ToolStripMenuItem();
                    fileMenu.Name = "fileMenu" + i.ToString();
                    fileMenu.Click += new EventHandler(fileMenu_Click);
                    this.StatusLabel_files.DropDownItems.Add(fileMenu);
                }
            }

            foreach (ToolStripMenuItem item in this.StatusLabel_files.DropDownItems)
            {
                item.Visible = false;
            }

            if (myApp.RecentFiles == null || myApp.RecentFiles.Files == null || myApp.RecentFiles.Files.Count == 0)
                return;

            Dictionary<string, string> dict = myApp.RecentFiles.Files;

            int c = 0;
            foreach (string item in dict.Keys)
            {
                fileMenu = this.StatusLabel_files.DropDownItems["fileMenu" + c++.ToString()] as ToolStripMenuItem;
                if (fileMenu != null)
                {
                    fileMenu.Text = dict[item];
                    fileMenu.Tag = item;
                    fileMenu.Visible = true;
                }
            }

            this.StatusLabel_files.ShowDropDown();
        }

        /// <summary>
        /// 点击文件按钮, 打开文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void fileMenu_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem m = sender as ToolStripMenuItem;

            if (File.Exists(m.Text))
            {
                System.Diagnostics.Process.Start(m.Text);
            }
            //else if (m.Tag != null && m.Tag.ToString() !="")
            //{
            //    //文件不存在, 修改记录
            //    Program.RecentFiles.RemoveHistory(m.Tag.ToString());
            //}
        }

        #endregion 最近的文件
        

        #region 窗体打开,关闭事件

        private void MenuForm_Load(object sender, EventArgs e)
        {
            //读取上次用户打开的位置
            int p = IniSet.ReadIniData(UserBll.CurrentUser?.Name, "menupage", "0").IsNull(0);
            this.MenuTab.SelectedIndex = Math.Min(p, this.outlookBar.Buttons.Count-1);
        
            this.outlookBar.SelectedButton = this.outlookBar.Buttons[this.MenuTab.SelectedIndex];

            //隐藏标签文本
            this.MenuTab.Region = new Region(new RectangleF(this.tabPage1.Left, this.tabPage1.Top, this.tabPage1.Width, this.tabPage1.Height));

            ////系统更新事件, 基础资料更新事件
            //SyncBasicInfo syncBasicInfo = new SyncBasicInfo();
            //syncBasicInfo.AppUpdateEvent += new SyncBasicInfo.AppUpdateHandler(syncBasicInfo_AppUpdateEvent);

            this.btn_changeUser.TransparentBackground(this.pictureBox1);
            this.btn_permission.TransparentBackground(this.pictureBox1);
            this.label_title.TransparentBackground(this.pictureBox1);
        }

        private void MenuForm_FormClosing(object sender, FormClosingEventArgs e)
        {
#if DEBUG 
            //记录当前打开的位置
            int p = this.MenuTab.SelectedIndex;
            IniSet.WriteIniData(UserBll.CurrentUser.Name, "menupage", p.ToString());
#else
            //提示
            if (MessageBox.Show(CN.Msg_CloseForm, Properties.Resources.systemInformation,
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question) == DialogResult.Yes)
            {
                //记录当前打开的位置
                int p = this.MenuTab.SelectedIndex;
                IniSet.WriteIniData(UserBll.CurrentUser.Name, "menupage", p.ToString());
            }
            else
            {
                e.Cancel = true;
            }
#endif

        }

        #endregion 窗体打开,关闭事件







        #region 其他

        /// <summary> 共享修复 </summary>
        private void other_okShare_Click(object sender, EventArgs e)
        {
            string batFile = "Computer\\OKShare.bat";
            System.Diagnostics.Process.Start(batFile);
        }


        private void other_remoteDesktop_Click(object sender, EventArgs e)
        {
        }

        private void other_update_Click(object sender, EventArgs e)
        {
            //更新
            if (MessageBox.Show("程序更新将会关闭当前程序, 请先保存后再更新!",
                Properties.Resources.systemInformation, MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
            {
                return;
            }


            //如果登录前没有检查更新, 在这里检查
            string cataIni = IniSet.ReadIniData("server", "catalog", ""); //服务器数据库
            var ser = IniSet.ReadIniData("server", "address", "");
            if (myApp.AppUpdate(DB.FSql.Ado.ConnectionString))
            {
                  //需要更新, 退出程序
                  Application.Exit();
            }

        }

        /// <summary> 测试 </summary>
        private void other_Test_Click(object sender, EventArgs e)
        {
            //JClassifyGroupDialog dialog = new JClassifyGroupDialog("TemplateVoucher");
            //dialog.ShowDialog();

            //VoucherReport.VoucherFuns.AddFuns();

            //Gtong.VoucherReport.CustomerReportEditor edit = new CustomerReportEditor();
            //edit.Show();

            //var bll = new BLL.BasicInfo.JSystemProfileBll();
            //var c= bll.GetCompany();

            //Task.Run(async () =>
            //{
            //    await Task.Delay(3000);
            //    MessageBox.Show("1111");
            //});

            //MessageBox.Show("Test");

           //await new PostPriceBllUI().Jiancha();



        }



        #endregion 其他


        #region 打印模板编辑

        /// <summary> 打印模板编辑 </summary>
        private void other_PrintTemplateEditor_Click(object sender, EventArgs e)
        {
            //GtPrintEditor.EditorForm form = new EditorForm();

            //
            //form.Show();
        }

        /// <summary> 读取模板文件前, 先从服务器下载系统模板 </summary>
        public static void TemplateForm_ReadingTemplate(string printTemplatePath)
        {
            //if (_templateBll == null)
            //{
            //    _templateBll = new PrintTemplateBll();
            //}

            //List<PrintTemplate> list = _templateBll.Query(null, null, "");

            ////保存文件

            //if (Directory.Exists(printTemplatePath) == false)
            //{
            //    Directory.CreateDirectory(printTemplatePath);
            //}

            //foreach (var template in list)
            //{
            //    string tempFile = Path.Combine(printTemplatePath, template.Name + ".json");

            //    using (System.IO.StreamWriter file = File.CreateText(tempFile))
            //    {
            //        file.Write(template.Json);
            //    }
            //}
        }

        /// <summary> 保存了模板后,如果是系统模板保存到服务器 </summary>
        public static void TemplateForm_Saved(PrintDocument doc, string jsonFile)
        {
            //if (_templateBll == null)
            //{
            //    _templateBll = new PrintTemplateBll();
            //}

            ////带有类型名称的序列化, 在序列化接口属性时使用这个
            //JsonSerializer serializer = new JsonSerializer { TypeNameHandling = TypeNameHandling.All };

            //PrintTemplate template = new PrintTemplate()
            //{
            //    Name = doc.TemplateName,
            //    isdel = false,
            //    Json = JObject.FromObject(doc, serializer).ToString(),
            //};
            
            //if (_templateBll.Save(template, UserBll.CurrentUser, out var err) == false)
            //{
            //    MessageBox.Show(err, Resources.systemInformation, MessageBoxButtons.OK,
            //        MessageBoxIcon.Warning);
            //}
        }

        //private static Bll.PrintTemplateBll _templateBll;

        #endregion 打印模板编辑





        #region 基础资料

        private void basic_accessory_Click(object sender, EventArgs e)
        {
            myApp.MainDock.AddForm2Layer<CommonTools.Basic.BasicInfoForm>();
        }


        private void basic_FixedAssetCard_Click(object sender, EventArgs e)
        {
            //var form = new FixedAssetCard();
            //form.Show();
        }

        private void basic_JFAGroup_Click(object sender, EventArgs e)
        {
            //var form = new JFAGroupForm();
            //form.Show();
        }

        private void basic_FixedAssetCardList_Click(object sender, EventArgs e)
        {
            //myApp.MainDock.AddForm2Layer<FixedAssetCardListForm>();

        }


        private void basic_Accounts_Click(object sender, EventArgs e)
        {
            //myApp.MainDock.AddForm2Layer<AccountsForm>();
        }

        /// <summary> 科目期初数据维护 </summary>
        private void basic_AccountsBalance_Click(object sender, EventArgs e)
        {
            //myApp.MainDock.AddForm2Layer<BasicInfo.AccountBalanceForm>();
        }

        /// <summary> 系统设置 </summary>
        private void basic_systemProfile_Click(object sender, EventArgs e)
        {
            //myApp.MainDock.AddForm2Layer<BasicInfo.SystemProfileForm>();

        }
        /// <summary> 基础资料设计 </summary>
        private void basic_design_Click(object sender, EventArgs e)
        {
            myApp.MainDock.AddForm2Layer(new CommonTools.Basic.BasicDesignForm());
        }

        private void basic_BeginData_Click(object sender, EventArgs e)
        {
            //myApp.MainDock.AddForm3Layer<BeginDataForm, BeginDataBll>();
            
        }



        #endregion
         
        private void other_DbBackup_Click(object sender, EventArgs e)
        {
            //string err = "";
            //SaveFileDialog saveFile = new SaveFileDialog();
            //saveFile.Title = "请选择保存文件路径";
            //saveFile.Filter = "数据库备份(*.bak)|*.bak";
            ////saveFile.OverwritePrompt = false;  //是否覆盖当前文件
            //saveFile.FileName = "Db" + DateTime.Now.ToString("yyyyMMddhhmmss");
            //saveFile.RestoreDirectory = true;  //保存对话框是否记忆上次打开的目录
            //if (saveFile.ShowDialog() == DialogResult.OK)
            //{
            //    BLL.BasicInfo.DbHelperBll dbHelper = new BLL.BasicInfo.DbHelperBll();
            //    string path = saveFile.FileName;
            //    string sqlBackup = "BACKUP DATABASE GtSoft TO DISK = '" + path + "'";
            //    dbHelper.DbBackup(sqlBackup, out err);
            //    MessageBox.Show(err);
            //}
            //else
            //{
            //    return;
            //}
        }
         
        private void outlookBar_Load(object sender, EventArgs e)
        {

        }
         
        private void other_EditingClear_Click(object sender, EventArgs e)
        {
            myApp.MainDock.AddForm2Layer<BasicInfo.EditingClearForm>();
        }




        private void cash_bank_Click(object sender, EventArgs e)
        {
            //myApp.MainDock.AddForm3Layer<Finance.CashForm, CashBll>();
        }

        private void cash_book_Click(object sender, EventArgs e)
        {
            //myApp.MainDock.AddForm2Layer<Finance.CashListForm>();
        }

        private void cash_balanceReport_Click(object sender, EventArgs e)
        {
            //myApp.MainDock.AddForm2Layer<Finance.CashReportForm>();
        }


        private void cw_InvoicesImport_Click(object sender, EventArgs e)
        {
            //myApp.MainDock.AddForm3Layer<SInvoicesImportForm, SInvoicesImportBll>();
        }

        private void Ca_BankFinancingLoan_Click(object sender, EventArgs e)
        {
        }

        private void cw_FDExpense_Click(object sender, EventArgs e)
        {
            //myApp.MainDock.AddForm3Layer<FDExpenseForm, FDExpenseBll>();
        }

        private void cw_Voucher_Click(object sender, EventArgs e)
        {
            //myApp.MainDock.AddForm3Layer<VoucherForm, VoucherBll>();

        }

        private void cw_VoucherDetail_Click(object sender, EventArgs e)
        {
            //myApp.MainDock.AddForm2Layer(new VoucherChronologicalBook());
        }

        /// <summary> 凭证过帐 </summary>
        private void cw_VoucherPosted_Click(object sender, EventArgs e)
        {
            //VoucherPostedForm voucherPostedForm = new VoucherPostedForm();
            //voucherPostedForm.ShowDialog();
        }
        /// <summary> 期末结账 </summary>
        private void cw_VoucherEOPClosing_Click(object sender, EventArgs e)
        {

        }

        private void cw_CustomerReport_Click(object sender, EventArgs e)
        {

        }

        /// <summary> 凭证自动转账 </summary>
        private void cw_AutoCreateCoucher_Click(object sender, EventArgs e)
        {

        }

        /// <summary> 结转损益 </summary>
        private void cw_VoucherCarryDown_Click(object sender, EventArgs e)
        {

        }

        /// <summary> 利润表 </summary>
        private void cw_ProfitReport_Click(object sender, EventArgs e)
        {

        }

        /// <summary> 利润分配表 </summary>
        private void cw_ProfitDistributionReport_Click(object sender, EventArgs e)
        {

        }





        private void other_DownloadInstaller_Click(object sender, EventArgs e)
        {
            //下载安装包
            myApp.AppUpdate(DB.FSql.Ado.ConnectionString, true);
        }



        private void order_QueryExpress_Click(object sender, EventArgs e)
        {
            //myApp.MainDock.AddForm2Layer<Logi.QueryExpressForm>();
        }

        private void order_syncTrade_Click(object sender, EventArgs e)
        {
            new Logi.SyncTradeDialog().ShowDialog();

        }

        private void order_stockOut_Click(object sender, EventArgs e)
        {
            //myApp.MainDock.AddForm2Layer<Logi.QueryStockoutForm>();
            myApp.MainDock.AddForm2Layer<Logi.QueryStockoutForm>();
        }

        private void order_Config_Click(object sender, EventArgs e)
        {
            //myApp.MainDock.AddForm3Layer<LogisticsFeeConfigForm, LogisticsFeeConfigBll>();
            //myApp.MainDock.AddForm2LayerPageForm<LogisticsFeeConfigItem, LogisticsFeeConfigBll, LogisticsFeeConfigItemEditDialog>();
        }


        private void order_LogiInfo_Click(object sender, EventArgs e)
        {
            //myApp.MainDock.AddForm2Layer<LogiInfoForm>();
            myApp.MainDock.AddForm2LayerPageForm<LogiInfo, LogiInfoBllUI>();
        }

        private void order_LogiCalculate_Click(object sender, EventArgs e)
        {
            //myApp.MainDock.AddForm2Layer<LogiFeeReportForm>();
            //myApp.MainDock.AddForm2Layer<LogiInfoForm>();
        }

        private void order_importBill_Click(object sender, EventArgs e)
        {
            myApp.MainDock.AddForm2Layer<LogisticsBillForm>();
        }

        private void order_LogiImport_Click(object sender, EventArgs e)
        {
            myApp.MainDock.AddForm2Layer<LogisticsImportForm>();
        }

        private void order_tradeItem_Click(object sender, EventArgs e)
        {
            //myApp.MainDock.AddForm2Layer<QueryTradeItemForm>();
        }

        private void order_price_Click(object sender, EventArgs e)
        {
        }

        private void order_postPrice_Click(object sender, EventArgs e)
        {
            //myApp.MainDock.AddForm2LayerPageForm<PostPriceDto, PostPriceBllUI, PostPriceEditor>();
        }

        private void order_MultPrice_Click(object sender, EventArgs e)
        {
            //myApp.MainDock.AddForm2LayerPageForm<MultPostPrice, MultPostPriceBllUI>();
        }

        private void order_shopReward_Click(object sender, EventArgs e)
        {
            //myApp.MainDock.AddForm2LayerPageForm<ShopReward, ShopRewardBll>();
        }

        private void order_postQtyPrice_Click(object sender, EventArgs e)
        {
            //myApp.MainDock.AddForm2LayerPageForm<PostQtyPrice, PostQtyPriceBll>();
        }

        private void order_shuadan_Click(object sender, EventArgs e)
        {
            //myApp.MainDock.AddForm2LayerPageForm<Shuadan, ShuadanBll>();
        }


        private void order_DaifaAdd_Click(object sender, EventArgs e)
        {
            //myApp.MainDock.AddForm2LayerPageForm<DaifaAdd, DaifaAddBllUI>();
        }

        private void order_shuadanStock_Click(object sender, EventArgs e)
        {
            var form = new ShuadanConfigForm();
            form.ShowDialog();
        }

        private void order_bufa_Click(object sender, EventArgs e)
        {
            var form = new BufaConfigForm();
            form.ShowDialog();
        }

        private void order_PostCalc_Click(object sender, EventArgs e)
        {
            var form = new PostCalcStrategyEditor();
            form.ShowDialog();
        }

        private void order_calc_Click(object sender, EventArgs e)
        {
            var form = new PostCalcStrategyEditor2();
            form.ShowDialog();
        }

        private void daifa_daifa_Click(object sender, EventArgs e)
        {
            myApp.MainDock.AddForm2LayerPageForm<NeedBuyerInfo, NeedBuyerInfoBllUI > ();
        }

        private void order_specialPost_Click(object sender, EventArgs e)
        {
            //myApp.MainDock.AddForm2LayerPageForm<SpecialPost, SpecialPostBll>();
        }

        private void order_DaifaQtyPost_Click(object sender, EventArgs e)
        {
            //myApp.MainDock.AddForm2LayerPageForm<DaifaQtyPostDto, DaifaQtyPostBllUI, DaifaQtyPostEditor>();
        }

        private void basic_shop_Click(object sender, EventArgs e)
        {
            //myApp.MainDock.AddForm2LayerPageForm<Model.Wdtshop, shop.ShopBllUI>();
        }

        private void daifa_stockChatGroup_Click(object sender, EventArgs e)
        {
            myApp.MainDock.AddForm2LayerPageForm<Model.StockWechat, StockWechatBll>();
        }

        private void daifa_refund_Click(object sender, EventArgs e)
        {
            myApp.MainDock.AddForm3Layer<RefundRegistForm, RefundRegistBll>();
        }

        private void guanButton1_Click(object sender, EventArgs e)
        {
            myApp.MainDock.AddForm2Layer<RefundRegistRptForm>();
        }

        private void toolTask_Click(object sender, EventArgs e)
        {
            myApp.OpenJobsForm();
        }

        private void daifa_shopLogin_Click(object sender, EventArgs e)
        {
            myApp.MainDock.AddForm2LayerPageForm<Model.ShopLogin, ShopLoginBllUI>();
        }

        private void order_GoodsOperator_Click(object sender, EventArgs e)
        {
            //myApp.MainDock.AddForm2LayerPageForm<Model.GoodsOperator, GoodsOperatorBllUI>();
        }



        private void dai_RefundFrom_Click(object sender, EventArgs e)
        {
            //myApp.MainDock.AddForm2Layer<CommonTools.Basic.BasicInfoForm>();
            var basicForm = new CommonTools.Basic.BasicInfoForm(typeof(JRefundFrom));
            basicForm.WindowState = FormWindowState.Maximized;
            WinApi.SetForegroundWindow(basicForm.Handle);
            if (CommonConfig.MainDock != null)
            {
                CommonConfig.MainDock.AddForm2Layer(basicForm);
            }
            else
            {
                basicForm.Show();
            }
        }

        private void order_shopPerson_Click(object sender, EventArgs e)
        {
            //myApp.MainDock.AddForm2LayerPageForm<Model.ShopPerson, ShopPersonBllUI>();
        }

        private void btnRefundDoc_Click(object sender, EventArgs e)
        {
            myApp.MainDock.AddForm2Layer<RefundDocRptForm>();
        }

        private void daifa_RefundList_Click(object sender, EventArgs e)
        {
            myApp.MainDock.AddForm2Layer<RefundDocRptForm>();
        }
    }
}